package util

import (
	"bufio"
	"errors"
	logger "gitee.com/zaper/private-logger"
	"io"
	"os"
	"strings"
)

type Properties struct {
	Data map[string]string
}

func NewProperties() *Properties {
	return &Properties{
		Data: make(map[string]string),
	}
}

func Read(filePath string) (*Properties, error) {
	properties := NewProperties()
	file, err := os.Open(filePath)
	defer func() {
		err := file.Close()
		if err != nil {
			logger.Errorf("Close %s is error %s", filePath, err)
			return
		}
	}()
	if err != nil {
		logger.Errorf("Open %s is error %s", filePath, err)
		return nil, err
	}
	reader := bufio.NewReader(file)
	for {
		line, _, err := reader.ReadLine()
		if err != nil {
			if err == io.EOF {
				break
			}
			logger.Errorf("Read properties is fail %s", err)
			return nil, err
		}
		lineStr := strings.TrimSpace(string(line))
		if lineStr == "" {
			continue
		}
		arr := parseLineData(lineStr)
		properties.Data[arr[0]] = arr[1]
	}
	return properties, nil
}

func ParseStringToProperties(dataStr string) (*Properties, error) {
	if dataStr == "" {
		logger.Info("input info is empty")
		return nil, errors.New("input info is empty")
	}
	properties := NewProperties()
	strLineArr := strings.Split(dataStr, "\n")
	for _, line := range strLineArr {
		lineStr := strings.TrimSpace(string(line))
		if lineStr == "" {
			continue
		}
		arr := parseLineData(lineStr)
		properties.Data[arr[0]] = arr[1]
	}
	return properties, nil
}

func parseLineData(line string) [2]string {
	index := strings.Index(line, "=")
	if index == -1 {
		return [2]string{}
	}
	var dataArr [2]string
	dataArr[0] = strings.TrimSpace(line[:index])
	dataArr[1] = strings.ReplaceAll(strings.TrimSpace(line[index+1:]), "\"", "")
	return dataArr
}
